package com.babyshop.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.babyshop.domain.Product;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;

public class ProductDaoImpl implements ProductDao {

	@SessionTarget
	Session session;

	@TransactionTarget
	Transaction transaction;

	@Override
	public void saveOfUpdate(Product product) {
		try {
			session.saveOrUpdate(product);
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		}

	}

	@Override
	public void delete(int id) {
		try {
			Product product = (Product) session.get(Product.class, id);
			session.delete(product);
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		}

	}

	@Override
	public Product get(int id) {
		Product product = null;
		try {
			product = (Product) session.get(Product.class, id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return product;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Product> getAll() {
		List<Product> listProducts = null;
		try {
			listProducts = session.createQuery("from Product").list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return listProducts;
	}
}
